import { Button, Modal, Popover } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { unpackApi } from '@/apis'
import { UnpackListItem } from '@/apis/unpackTypes'
import {
  type ProTableProps,
  type ProTableRef,
  ProTable,
  SvgIcon
} from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import qrCode from '@/static/qrCode.png'
import { bus } from '@/utils'

import { TYPE_PARAMS } from '../types'
export default defineComponent({
  name: 'UnpackManage',
  setup() {
    const tableRef = ref({} as ProTableRef)
    const router = useRouter()
    const statusFilter = {
      0: '未开始',
      1: '进行中',
      2: '已结束'
    }
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入活动名称',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          {
            title: '活动名称',
            field: 'activityName'
          },
          {
            title: '活动开始时间',
            field: 'startTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '活动截止时间',
            field: 'endTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '链接地址',
            field: 'endTime',
            align: 'center',
            slots: {
              default: () => (
                <Popover
                  trigger={'hover'}
                  v-slots={{
                    content: () => (
                      <img
                        style={{ width: '140px', height: '140px' }}
                        src={qrCode}
                      />
                    )
                  }}
                >
                  <SvgIcon
                    name="qrCode"
                    style={{ width: '25px', height: '25px' }}
                  />
                </Popover>
              )
            }
          },
          {
            title: '状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return statusFilter[cellValue]
            }
          },
          {
            title: '创建时间',
            field: 'createTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            }
          }
        ],
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await unpackApi.getUnpackList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        },
        pagerConfig: {
          pageSize: 10
        }
      }
    } as ProTableProps)

    function handleAdd(type: TYPE_PARAMS, id?: number) {
      if (type === 'edit') {
        router.push({
          path: '/marketing/unpack/unpackEdit',
          query: {
            id
          }
        })
      } else {
        router.push({
          path: '/marketing/unpack/unpackCreate'
        })
      }
    }
    function handleClose(row: UnpackListItem) {
      if (row.status === 2) {
        Modal.confirm({
          title: '确认启用该活动？',
          onOk() {
            tableRef.value.refresh(async () => {
              unpackApi.updateActivityStatus({
                activityInfoId: row.id,
                status: 1
              })
            })
          }
        })
      } else {
        Modal.confirm({
          title: '确认关闭该活动？',
          onOk() {
            tableRef.value.refresh(async () => {
              await unpackApi.updateActivityStatus({
                activityInfoId: row.id,
                status: 2
              })
            })
          }
        })
      }
    }
    function gotoResult(id: number) {
      router.push({
        path: '/marketing/unpack/unpackResult',
        query: {
          id
        }
      })
    }

    onMounted(() => {
      bus.on('refreshUnpackList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      tableConfig,
      handleAdd,
      handleClose,
      gotoResult
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => (
              <Button type="primary" onClick={() => this.handleAdd('create')}>
                新增翻牌
              </Button>
            ),
            operation: ({ row }: { row: UnpackListItem }) => (
              <div>
                <Button
                  type="link"
                  onClick={() => this.handleAdd('edit', row.id)}
                >
                  编辑
                </Button>
                {row.status !== 2 ? (
                  <Button type="link" onClick={() => this.handleClose(row)}>
                    关闭
                  </Button>
                ) : null}

                <Button type="link" onClick={() => this.gotoResult(row.id)}>
                  翻牌结果
                </Button>
              </div>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
